import 'dart:async';

import 'package:flutter_plugin_record/flutter_plugin_record.dart';

import 'loding.dart';
import 'log_utils.dart';

enum SoundCall { playEnd, maxTime, initSuccess, recordEnd }

class SoundCallUtils {
  FlutterPluginRecord recordPlugin = FlutterPluginRecord();

  String filePath = "";

  //声音大小(分大五个等级: 从小到大1, 2, 3, 4, 5)
  int volume = 1;

  //录音时长
  int seconds = 0;

  bool isLimitTime = false; //是否要限制时长

  // 录音计时器。
  Timer? _timer;

  late Function call;
  Function? secondsAction;

  /// 启动录音计时器。
  void startTimer() {
    seconds = 0;
    // 计时器（`Timer`）组件的定期（`periodic`）构造函数，创建一个新的重复计时器。
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      LogUtilTool.println("seconds = $seconds");
      if (isLimitTime) {
        if (seconds == 59) {
          call(SoundCall.maxTime);
          stop();
          _timer?.cancel();
          xdShowToast("录制时长已经超出");
          return;
        }
      }
      if (secondsAction != null) {
        secondsAction!(seconds);
      }
      seconds++;
    });
  }

  //播放时长
  int playSeconds = 0;

  // 录音计时器。
  Timer? _playTimer;

  /// 启动播放计时器。
  void startPlayTimer() {
    playSeconds = 0;
    // 计时器（`Timer`）组件的定期（`periodic`）构造函数，创建一个新的重复计时器。
    _playTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      LogUtilTool.println("playSeconds");
      //该轮子没有音频播放完成回调，通过语音时长判断
      if (playSeconds == seconds) {
        stopPlay();
        _playTimer?.cancel();
        playEndCall!();
        return;
      }
      playSeconds++;
    });
  }

  void soundInit(Function function, {volumeAction, secondsAction, bool isLimitTime = true, bool isMp3Record = false}) {
    print('soundInit这里走了');
    if (isMp3Record) {
      recordPlugin.initRecordMp3();
    } else {
      initRecord();
    }

    this.isLimitTime = isLimitTime;
    call = function;
    this.secondsAction = secondsAction;
    ///初始化方法的监听
    recordPlugin.responseFromInit.listen((data) {
      if (data) {
        LogUtilTool.println("录音初始化成功");
        call(SoundCall.initSuccess);
      } else {
        LogUtilTool.println("录音初始化失败");
      }
    });

    /// 开始录制或结束录制的监听
    recordPlugin.response.listen((data) {
      if (data.msg == "onStop") {
        ///结束录制时会返回录制文件的地址方便上传服务器
        LogUtilTool.println("onStop  文件路径${data.path}");
        filePath = data.path.toString();
//        audioTime = data.audioTimeLength!.floor();
        LogUtilTool.println("onStop  时长 ${data.audioTimeLength}");
        seconds = data.audioTimeLength!.ceil() > 60
            ? 60
            : data.audioTimeLength!.ceil();
        LogUtilTool.println("seconds  时长 $seconds");
        call(SoundCall.recordEnd);
      } else if (data.msg == "onStart") {
        LogUtilTool.println("onStart --");
      } else {
        LogUtilTool.println("--其他${data.msg}");
      }
    });

    ///录制过程监听录制的声音的大小 方便做语音动画显示图片的样式
    recordPlugin.responseFromAmplitude.listen((data) {
      var voiceData = double.parse(data.msg.toString());
      LogUtilTool.println("振幅大小   $voiceData");
      LogUtilTool.println("时常大小   ${data.audioTimeLength}");
      int volume1 = 1;
      if (voiceData >= 0 && voiceData <= 0.08) {
        volume1 = 1;
      } else if (voiceData > 0.08 && voiceData <= 0.2) {
        volume1 = 2;
      } else if (voiceData > 0.2 && voiceData <= 0.35) {
        volume1 = 3;
      } else if (voiceData > 0.35 && voiceData <= 0.5) {
        volume1 = 4;
      } else if (voiceData > 0.5 && voiceData <= 1) {
        volume1 = 5;
      }
      if (volume1 != volume) {
        volume = volume1;
        if (volumeAction != null) {
          volumeAction(volume1);
        }
      }
    });

    recordPlugin.responsePlayStateController.listen((data) {
      LogUtilTool.println("播放状态   ${data.playState}");
      LogUtilTool.println("播放路径   ${data.playPath}");
      if ('complete' == data.playState) {
        _timer?.cancel();
        call(SoundCall.playEnd);
      }
    });
  }

  ///初始化语音录制的方法
  void initRecord() async {
    recordPlugin.init();
  }

  ///开始语音录制的方法
  void start() async {
    startTimer();
    recordPlugin.start();
  }

  ///根据传递的路径进行语音录制
  void startByWavPath(String wavPath) async {
    startTimer();
    recordPlugin.startByWavPath(wavPath);
  }

  ///停止语音录制的方法
  void stop() {
    recordPlugin.stop();
    _timer?.cancel();
  }

  ///播放语音的方法
  void play() {
    startPlayTimer();
    recordPlugin.play();
  }

  //播放非录制音频
  Function? playEndCall;

  ///播放指定路径录音文件  url为播放网络语音，file为播放本地语音文件
  void playByPath(String path, String type, Function function,
      {int? recordTime,bool startTimer = true}) {
    if (recordTime != null && recordTime > 0) {
      seconds = recordTime;
    }
    playEndCall = function;
    if(startTimer){
      startPlayTimer();
    }
    recordPlugin.playByPath(path, type);
  }

  ///暂停|继续播放
  void pause() {
    recordPlugin.pausePlay();
  }

  ///停止播放
  void stopPlay() {
    recordPlugin.stopPlay();
    _timer?.cancel();
    _playTimer?.cancel();
  }

  void destroy() {
    /// 当界面退出的时候是释放录音资源
    stopPlay();
    stop();
    recordPlugin.dispose();
    _timer?.cancel();
    _playTimer?.cancel();
  }
}